package org.linlinjava.litemall.wx.service;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.linlinjava.litemall.core.exception.BadRequestException;
import org.linlinjava.litemall.core.kdniao.dto.Order;
import org.linlinjava.litemall.core.util.ExportExcelUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.linlinjava.litemall.core.kdniao.dto.KdniaoCreateOrderDto;
import org.linlinjava.litemall.db.util.ExcelHeaderTemplateConstant;
import org.linlinjava.litemall.wx.dto.AdminRenOrderDetail;
import org.linlinjava.litemall.wx.dto.RentOrderDto;
import org.linlinjava.litemall.db.util.RentOrderConstant;
import org.linlinjava.litemall.core.kdniao.dto.KdniaoCreateOrderResultDto;
import org.linlinjava.litemall.core.kdniao.enums.ShipperCodeEnum;
import org.linlinjava.litemall.core.kdniao.service.KdniaoService;
import org.linlinjava.litemall.core.kdniao.util.KdniaoUtil;
import org.linlinjava.litemall.db.dto.ReturnBookDto;
import org.linlinjava.litemall.wx.dto.WechatSendTemplate;
import org.linlinjava.litemall.wx.util.SnUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static org.linlinjava.litemall.db.util.RentOrderConstant.*;

/**
 * @author Administrator
 */
@Service("rentOrder-pay")
public class WxRentOrderService {
    @Resource
    private LitemallRentOrderMapper rentOrderMapper;
    @Autowired
    private LitemallGoodsProductService goodsProductService;
    @Autowired
    private LitemallUserMemberService userMemberService;
    @Autowired
    private LitemallAddressService addressService;
    @Autowired
    private LitemallRentOrderService rentOrderService;
    @Resource
    private LitemallUserService userService;
    @Autowired
    private KdniaoService kdniaoService;
    @Autowired
    private LitemallRentOrderDetailService rentOrderDetailService;
    @Resource
    private LitemallRentOrderDetailMapper rentOrderDetailMapper;
    @Resource
    private LitemallBookBoxMapper bookBoxMapper;
    @Resource
    private LitemallMemberRuleMapper memberRuleMapper;
    @Resource
    private LitemallOrderService orderService;
    @Autowired
    private LitemallBookBoxService bookBoxService;
    @Autowired
    private GoodsProductMapper goodsProductMapper;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallRentOrderChangeMapper rentOrderChangeMapper;
    @Autowired
    private LitemallUserMapper userMapper;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private LitemallGoodsProductService productService;

    /**
     * 提交租书订单
     *
     * @param userId
     * @param rentOrderDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object submitRentOrder(Integer userId, RentOrderDto rentOrderDto) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer addressId = rentOrderDto.getAddressId();
        Integer[] bookBoxIds = rentOrderDto.getBookBoxIds();
        if (bookBoxIds == null || bookBoxIds.length == 0) {
            return ResponseUtil.fail(400, "必要参数没传");
        }
        String remark = rentOrderDto.getRemark();
        LitemallAddress checkedAddress = addressService.query(userId, rentOrderDto.getAddressId());
        if (checkedAddress == null) {
            return ResponseUtil.badArgument();
        }
        LitemallUserMember userMember = userMemberService.findByUid(userId);
        if (userMember == null) {
            return ResponseUtil.fail(500, "请先开通会员");
        }
        if (!userService.findById(userId).getHasPayDeposit()) {
            return ResponseUtil.fail(500, "请至会员页缴纳押金");
        }
        Integer memberRuleId = userMember.getMemberRuleId();
        LitemallMemberRule memberRule = memberRuleMapper.selectByPrimaryKey(memberRuleId);
        int num = 0;
        for (Integer bookBoxId : bookBoxIds) {
            LitemallBookBox bookBox = bookBoxService.findById(bookBoxId);
            if (bookBox != null) {
                Integer number = bookBox.getNumber();
                num += number;
            }
        }
        // todo  改为书位拦截
//        if (num != memberRule.getAvailableRentNumber()) {
//            return ResponseUtil.fail(500, "下单本书只能为" + memberRule.getAvailableRentNumber() + "本");
//        }
        if (checkHasBookToReturn(userId)) {
            return ResponseUtil.fail(500, "您尚有待还的书，请归还后再借");
        }
        if (addressId == null) {
            return ResponseUtil.fail(500, "请选择收货地址");
        }
        /* 更新订单表 */
        LitemallRentOrder rentOrder = new LitemallRentOrder();
        rentOrder.setUserId(userId);
        rentOrder.setUserName(userService.findById(userId).getNickname());
        rentOrder.setUserMemberId(userMember.getId());
        String consignee = checkedAddress.getName();
        rentOrder.setConsignee(consignee);
        String mobile = checkedAddress.getTel();
        rentOrder.setMobile(mobile);
        if (!StringUtils.isEmpty(remark)) {
            rentOrder.setRemark(remark);
        }

        String detailedAddress = checkedAddress.getProvince() + " " + checkedAddress.getCity() + " " + checkedAddress.getCounty() + " " + checkedAddress.getAddressDetail();
        rentOrder.setAddress(detailedAddress);
        rentOrder.setRentOrderStatus(RentOrderConstant.STATUS_WAIT);
        rentOrder.setRentOrderSn(SnUtil.generateOrderSn("rent"));
        rentOrder.setAddTime(LocalDateTime.now());
        rentOrder.setUpdateTime(LocalDateTime.now());
        rentOrderMapper.insertSelective(rentOrder);
        int count = 0;
        /* 更新订单详情表 */
        for (Integer bookBoxId : bookBoxIds) {
            LitemallBookBox bookBox = bookBoxService.findById(bookBoxId);
            LitemallGoodsProduct goodsProduct = goodsProductService.findById(bookBox.getGoodsProductId());
            if (goodsProductMapper.reduceStock(goodsProduct.getId(), bookBox.getNumber()) == 0) {
                Integer goodsId = goodsProduct.getGoodsId();
                LitemallGoods goods = goodsService.findById(goodsId);
                throw new BadRequestException(HttpStatus.BAD_REQUEST, goods.getName() + " 库存不足");
            }
            LitemallRentOrderDetail rentOrderDetail = new LitemallRentOrderDetail();
            rentOrderDetail.setUserId(userId);
            rentOrderDetail.setName(bookBox.getName());
            rentOrderDetail.setRentOrderId(rentOrder.getId());
            rentOrderDetail.setPrice(bookBox.getOriginalPrice());
            rentOrderDetail.setMemberPrice(goodsProduct.getMemberPrice());
            rentOrderDetail.setPicUrl(bookBox.getPicUrl());
            rentOrderDetail.setGoodsProductId(bookBox.getGoodsProductId());
            rentOrderDetail.setGoodsId(bookBox.getGoodsId());
            rentOrderDetail.setAuthor(bookBox.getAuthor());
            count += bookBox.getNumber();
            rentOrderDetail.setNumber(bookBox.getNumber());
            rentOrderDetail.setAddTime(LocalDateTime.now());
            rentOrderDetail.setUpdateTime(LocalDateTime.now());
            rentOrderDetailMapper.insertSelective(rentOrderDetail);
            bookBoxMapper.deleteByPrimaryKey(bookBoxId);
        }

        // TODO
        //   调用微信公众公众号发送信息
        //



        LitemallUser litemallUser = userMapper.selectByPrimaryKey(userId);
        // 获取用户信息
        String openid = litemallUser.getWeixinOpenid();

        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId("Wctb0VVfwYhdHsZzywD8VC2ZQy6p8pD2ltBUJK6L-hg");
        //设置发送给哪个用户
        //wxMpTemplateMessage.setToUser("o2mFx6hQ4X-vkExEUozjncLnry9k");
        wxMpTemplateMessage.setToUser(litemallUser.getUsername());
        //构建消息格式
        List<WxMpTemplateData> list = Arrays.asList(
                new WxMpTemplateData("first", "您的订单已经确认成功"),
                //订单号
                new WxMpTemplateData("keyword1", rentOrder.getRentOrderSn()),
                new WxMpTemplateData("keyword2", "共计图书：" + count + "本"),
                new WxMpTemplateData("keyword3", ""),
                new WxMpTemplateData("remark", "请您阅读愉快")
        );
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(list);
        try {
            Map<String,String> map=new HashMap<>();
            map.put("first", "您的订单已经确认成功");
            map.put("keyword1", rentOrder.getRentOrderSn());
            map.put("keyword2", "共计图书：" + count + "本");
            map.put("keyword3", "");
            map.put("remark", "请您阅读愉快");

//            WechatSendTemplate.sendTemplate(openid,
//                    rentOrder.getRentOrderSn(),
//                    "共计图书：" + count + "本",
//                    "",
//                    "请您阅读愉快");

            //发送模板
//            String s = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
//            System.out.println(s);
        } catch (Exception e) {
            System.out.println("===========发送模板信息失败===========");
            e.printStackTrace();

        }


        return ResponseUtil.ok(rentOrder);
    }

    /**
     * 确认租书订单
     *
     * @param userId
     * @param rentOrderDto
     * @return
     */
    public Object checkOut(Integer userId, RentOrderDto rentOrderDto) {
        Integer addressId = rentOrderDto.getAddressId();
        Integer[] bookBoxIds = rentOrderDto.getBookBoxIds();
        LitemallAddress checkedAddress;
        if (addressId == null || addressId.equals(0)) {
            checkedAddress = addressService.findDefault(userId);
            if (checkedAddress == null) {
                checkedAddress = new LitemallAddress();
                checkedAddress.setId(0);
                addressId = 0;
            } else {
                addressId = checkedAddress.getId();
            }

        } else {
            checkedAddress = addressService.query(userId, addressId);
            // 如果null, 则报错
            if (checkedAddress == null) {
                return ResponseUtil.fail(400, "错误的参数 addressId");
            }
        }
        List<LitemallBookBox> checkedBookBoxList = new ArrayList<>();
        Integer booDigitSum = 0;
        // todo 验证数位
        for (Integer bookBoxId : bookBoxIds) {
            LitemallBookBox bookBox = bookBoxService.findById(bookBoxId);
            booDigitSum += (bookBox.getBookDigit() * bookBox.getNumber());
            checkedBookBoxList.add(bookBox);
        }
        // 暂时去掉书位限制
//        if (booDigitSum < 10) {
//            return ResponseUtil.fail(400, "数位不足10，请再多选几本吧");
//        }
        Map<String, Object> data = new HashMap<>();
        data.put("checkedAddress", checkedAddress);
        data.put("checkedBookBoxList", checkedBookBoxList);
        data.put("addressId", addressId);
        return data;
    }


    /**
     * 检查是否有待还的书
     *
     * @param userId
     * @return
     */
    public Boolean checkHasBookToReturn(Integer userId) {
        List<LitemallRentOrder> rentOrders = rentOrderService.queryAllByUserId(userId);
        if (rentOrders == null || rentOrders.size() == 0) {
            return false;
        } else {
//            return rentOrders.stream().anyMatch(rentOrder -> rentOrder.getRentOrderStatus() <= STATUS_CONFIRM);
            return rentOrderService.getReturnBooksCount(userId)>=10;
        }
    }


    /**
     * 查看我的租借订单
     *
     * @param userId
     * @param status
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    public Object queryList(Integer userId, Integer status, Integer page, Integer limit, String sort, String order) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.okList(rentOrderService.querySelective(userId, status, page, limit, sort, order));
    }

    /**
     * 用户确认收货
     *
     * @param userId
     * @param rentOrderId
     * @return
     */
    public Object confirm(Integer userId, Integer rentOrderId) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        if (rentOrderId == null) {
            return ResponseUtil.badArgument();
        }
        LitemallRentOrder rentOrder = rentOrderService.findById(userId, rentOrderId);
        if (rentOrder == null) {
            return ResponseUtil.badArgument();
        }
        if (!rentOrder.getRentOrderStatus().equals(STATUS_SHIP)) {
            return ResponseUtil.fail(400, "尚未发货，暂不能确认收货");
        }
        if (!rentOrder.getUserId().equals(userId)) {
            return ResponseUtil.badArgumentValue();
        }
        rentOrder.setRentOrderStatus(STATUS_CONFIRM);
        rentOrder.setConfirmTime(LocalDateTime.now());


        //  添加订单状态改变日期
        LitemallRentOrderChange orderChange = new LitemallRentOrderChange();
        orderChange.setRentOrderId(rentOrder.getId());
        orderChange.setRentOrderSn(rentOrder.getRentOrderSn());
        orderChange.setRentOrderTimeStatus(STATUS_CONFIRM);
        orderChange.setAddTime(LocalDateTime.now());
        orderChange.setUpdateTime(LocalDateTime.now());
        orderChange.setOrderStatusChangeTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        orderChange.setDeleted(false);
        rentOrderChangeMapper.insert(orderChange);
        rentOrderService.updateById(rentOrder);

        return ResponseUtil.ok(rentOrderId);
    }

    public Object cancel(Integer userId, Integer rentOrderId) {
        LitemallRentOrder rentOrder = rentOrderService.findByIdAndUserId(rentOrderId, userId);
        if (rentOrder == null || !userId.equals(rentOrder.getUserId())) {
            return ResponseUtil.fail(500, "未找到该订单");
        }
        if (rentOrder.getRentOrderStatus() >= STATUS_SHIP) {
            return ResponseUtil.fail(500, "订单已发货不能取消");
        }
        rentOrder.setUpdateTime(LocalDateTime.now());
        rentOrder.setRentOrderStatus(STATUS_CANCEL);

        //  添加订单状态改变日期
        LitemallRentOrderChange orderChange = new LitemallRentOrderChange();
        orderChange.setRentOrderId(rentOrder.getId());
        orderChange.setRentOrderSn(rentOrder.getRentOrderSn());
        orderChange.setRentOrderTimeStatus(STATUS_CANCEL);
        orderChange.setAddTime(LocalDateTime.now());
        orderChange.setUpdateTime(LocalDateTime.now());
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        orderChange.setOrderStatusChangeTime(time);
        orderChange.setDeleted(false);
        rentOrderChangeMapper.insert(orderChange);


        rentOrderMapper.updateByPrimaryKeySelective(rentOrder);

        List<LitemallRentOrderDetail> rentOrderDetails = rentOrderDetailService.queryByOid(rentOrderId);
        for (LitemallRentOrderDetail rentOrderDetail : rentOrderDetails) {
            goodsProductMapper.addStock(rentOrderDetail.getGoodsId(), rentOrderDetail.getNumber());
        }

        return ResponseUtil.ok(rentOrder);
    }

    /**
     * 逻辑删除订单
     *
     * @param rentOrderId
     * @return
     */
    public Object logicalDelete(Integer rentOrderId) {
        rentOrderService.logicalDeleteById(rentOrderId);
        rentOrderDetailService.deleteByOid(rentOrderId);
        return ResponseUtil.ok();
    }

    /**
     * 对接快递鸟发送租书物流
     *
     * @param rentOrderId
     * @return
     */
    public Object rentExpress(Integer rentOrderId) {
        LitemallRentOrder rentOrder = rentOrderService.findById(rentOrderId);
        if (!rentOrder.getRentOrderStatus().equals(STATUS_WAIT)) {
            return ResponseUtil.fail(500, "该订单不能发货");
        }
        /* 对接快递鸟物流 start */
        KdniaoCreateOrderDto kdniaoCreateOrderDto = new KdniaoCreateOrderDto();
        //设置快递公司编号
        kdniaoCreateOrderDto.setShipperCode(ShipperCodeEnum.ZHONGTONG.getName());
        //设置订单号
        kdniaoCreateOrderDto.setOrderCode(rentOrder.getId().toString());
        //设置系统发件人信息
        kdniaoCreateOrderDto.setSender(KdniaoUtil.buildSystemSender());
        //设置收件人信息
        kdniaoCreateOrderDto.setReceiver(KdniaoUtil.buildReceiver(rentOrder));
        List<LitemallRentOrderDetail> rentOrderDetails = rentOrderDetailService.queryByOid(rentOrderId);
        //设置商品信息
        kdniaoCreateOrderDto.setCommodity(KdniaoUtil.buildCommodity(rentOrderDetails));

        KdniaoCreateOrderResultDto result;
        try {
            result = kdniaoService.orderOnlineByJson(kdniaoCreateOrderDto);
        } catch (Exception e) {
            return ResponseUtil.fail(500, "发送物流失败");
        }
        /* 对接快递鸟物流 end */

        rentOrder.setRentOrderStatus(STATUS_SHIP);
        rentOrder.setShipSn(result.getOrder().getLogisticCode());
        rentOrder.setShipChannel(result.getOrder().getShipperCode());
        rentOrder.setShipTime(LocalDateTime.now());
        rentOrderService.updateById(rentOrder);

        return ResponseUtil.ok(rentOrder.getShipSn());
    }

    public Object returnBooks(Integer userId, ReturnBookDto returnBookDto) {
        Integer rentOrderId = returnBookDto.getRentOrderId();
        LocalDate shipBackSubscribeTime = returnBookDto.getShipBackSubscribeTime();
        String shipBackSubscribeDetailTime = returnBookDto.getShipBackSubscribeDetailTime();
        LitemallRentOrder rentOrder = rentOrderService.findByIdAndUserId(rentOrderId, userId);
        if (rentOrder == null) {
            return ResponseUtil.fail(400, "该订单不存在");
        }
        if (!rentOrder.getRentOrderStatus().equals(STATUS_CONFIRM)) {
            return ResponseUtil.fail(400, "该状态不能还书");
        }
        rentOrder.setRentOrderStatus(STATUS_RETURN_WAIT);
        rentOrder.setShipBackSubscribeTime(shipBackSubscribeTime);
        rentOrder.setShipBackSubscribeDetailTime(shipBackSubscribeDetailTime);

        //  添加订单状态改变日期
        LitemallRentOrderChange orderChange = new LitemallRentOrderChange();
        orderChange.setRentOrderId(rentOrder.getId());
        orderChange.setRentOrderSn(rentOrder.getRentOrderSn());
        orderChange.setRentOrderTimeStatus(STATUS_RETURN_WAIT);
        orderChange.setAddTime(LocalDateTime.now());
        orderChange.setUpdateTime(LocalDateTime.now());
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        orderChange.setOrderStatusChangeTime(time + " 预约时间：" + returnBookDto.getShipBackSubscribeTime() + "  " + returnBookDto.getShipBackSubscribeDetailTime());
        orderChange.setDeleted(false);
        rentOrderChangeMapper.insert(orderChange);

        rentOrderService.updateById(rentOrder);
        return ResponseUtil.ok(rentOrder);
    }

    /**
     * 对接快递鸟还书发送物流 （目前用不上）
     *
     * @param rentOrderId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object rentBackExpress(Integer rentOrderId) {
        LitemallRentOrder rentOrder = rentOrderService.findById(rentOrderId);
        if (rentOrder == null) {
            return ResponseUtil.fail(500, "该订单不存在");
        }
        if (!rentOrder.getRentOrderStatus().equals(STATUS_RETURN_WAIT)) {
            return ResponseUtil.fail(500, "不是待还书状态，不能还书");
        }
        /* 对接快递鸟物流 start */
        KdniaoCreateOrderDto kdniaoCreateOrderDto = new KdniaoCreateOrderDto();
        //设置快递公司编号
        kdniaoCreateOrderDto.setShipperCode(ShipperCodeEnum.ZHONGTONG.getName());
        //设置订单号
        kdniaoCreateOrderDto.setOrderCode("back" + rentOrder.getId().toString());
        //设置系统发件人信息
        kdniaoCreateOrderDto.setSender(KdniaoUtil.buildSender(rentOrder));
        //设置收件人信息
        kdniaoCreateOrderDto.setReceiver(KdniaoUtil.buildSystemReceiver());
        List<LitemallRentOrderDetail> rentOrderDetails = rentOrderDetailService.queryByOidAndStatus(rentOrderId);
        //设置商品信息
        kdniaoCreateOrderDto.setCommodity(KdniaoUtil.buildCommodity(rentOrderDetails));

        KdniaoCreateOrderResultDto result;
        try {
            result = kdniaoService.orderOnlineByJson(kdniaoCreateOrderDto);
        } catch (Exception e) {
            return ResponseUtil.fail(500, "发送物流失败");
        }
        /* 对接快递鸟物流 end */
        rentOrder.setRentOrderStatus(STATUS_RETURN_SHIP);
        rentOrder.setShipSn(result.getOrder().getLogisticCode());
        rentOrder.setShipChannel(result.getOrder().getShipperCode());
        rentOrder.setShipTime(LocalDateTime.now());
        rentOrderService.updateById(rentOrder);

        return ResponseUtil.ok(rentOrder.getShipSn());
    }


    /**
     * 将 买书/租书 订单中待发货的订单导出
     *
     * @param type
     * @param response
     * @return
     */
    public Object exportExcel(String type, HttpServletResponse response) {
        String[] header = null;
        List<List<String>> body = null;
        if (type.equals("买书")) {
            header = ExcelHeaderTemplateConstant.ORDER_HEADER_TEMPLATE;
            body = new ArrayList<>();

            List<LitemallOrder> litemallOrders = orderService.queryByShipWait();
            if (litemallOrders == null) {
                return ResponseUtil.fail(400, "没有待发货订单");
            }
            for (LitemallOrder litemallOrder : litemallOrders) {
                List<String> fieldList = new ArrayList<>();
                fieldList.add(litemallOrder.getConsignee());
                fieldList.add(litemallOrder.getOrderSn());
                fieldList.add(litemallOrder.getAddTime().toString());
                fieldList.add(litemallOrder.getAddress());
                fieldList.add(litemallOrder.getMobile());
                body.add(fieldList);
            }

        }
        if (type.equals("租书")) {
            header = ExcelHeaderTemplateConstant.RENT_ORDER_HEADER_TEMPLATE;
            body = new ArrayList<>();


            /* 租书待发货订单 */
            LitemallRentOrderExample example = new LitemallRentOrderExample();
            example.or().andRentOrderStatusEqualTo(STATUS_WAIT).andDeletedEqualTo(false);
            List<LitemallRentOrder> rentOrders = rentOrderMapper.selectByExample(example);

            /* 还书待发货订单 */
            LitemallRentOrderExample rentOrderBackExample = new LitemallRentOrderExample();
            example.or().andRentOrderStatusEqualTo(STATUS_RETURN_WAIT).andDeletedEqualTo(false);
            List<LitemallRentOrder> rentBackOrders = rentOrderMapper.selectByExample(rentOrderBackExample);

            if (rentBackOrders == null || rentOrders == null) {
                return ResponseUtil.fail(400, "没有待发货订单");
            }

            for (LitemallRentOrder rentOrder : rentOrders) {
                List<String> fieldList = new ArrayList<>();
                fieldList.add("租书");
                fieldList.add(rentOrder.getConsignee());
                fieldList.add(rentOrder.getRentOrderSn());
                fieldList.add(rentOrder.getAddress());
                fieldList.add(rentOrder.getMobile());
                fieldList.add(rentOrder.getShipBackSubscribeTime().toString());
                body.add(fieldList);
            }

            for (LitemallRentOrder rentBackOrder : rentBackOrders) {
                List<String> fieldList = new ArrayList<>();
                fieldList.add("租书");
                fieldList.add(rentBackOrder.getConsignee());
                fieldList.add(rentBackOrder.getRentOrderSn());
                fieldList.add(rentBackOrder.getAddress());
                fieldList.add(rentBackOrder.getMobile());
                fieldList.add(rentBackOrder.getShipBackSubscribeTime().toString());
                body.add(fieldList);
            }
        }
        HSSFWorkbook sheets = ExportExcelUtil.expExcel(header, body);
        String fileName = type + "待发货报表.xls";
        ExportExcelUtil.outFile(sheets, "D:\\" + fileName, response);
        return ResponseUtil.ok("已导出到您的D盘");
    }

    /**
     * 获取租书订单物流轨迹
     *
     * @param rentOrderId
     * @return
     */
    public Object getExpressTrace(Integer rentOrderId) {
        LitemallRentOrder rentOrder = rentOrderService.findById(rentOrderId);
        if (rentOrder == null) {
            return ResponseUtil.fail(400, "该订单不存在");
        }
        if (rentOrder.getShipWay().equals(1)) {
            return ResponseUtil.ok("同城配送，今日必达！");
        }
        try {
            return ResponseUtil.ok(kdniaoService.getOrderTracesByJson(new Order(rentOrder.getRentOrderSn(), rentOrder.getShipChannel(), rentOrder.getShipSn())));
        } catch (Exception e) {
            return ResponseUtil.fail(500, "获取物流轨迹失败");
        }
    }

    /**
     * 管理员替用户下单
     *
     * @param rentOrderDto
     * @return
     */
    @Transactional
    public Object submitRentOrder(RentOrderDto rentOrderDto) {
        Integer userId = rentOrderDto.getUserId();

        List<AdminRenOrderDetail> detailList = rentOrderDto.getDetailList();
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        Integer addressId = rentOrderDto.getAddressId();
//        Integer[] bookBoxIds = rentOrderDto.getBookBoxIds();
//        if (bookBoxIds == null || bookBoxIds.length == 0) {
//            return ResponseUtil.fail(400, "必要参数没传");
//        }
        String remark = rentOrderDto.getRemark();
        LitemallAddress checkedAddress = addressService.query(userId, rentOrderDto.getAddressId());
        if (checkedAddress == null) {
            return ResponseUtil.badArgument();
        }
        LitemallUserMember userMember = userMemberService.findByUid(userId);
        if (userMember == null) {
            return ResponseUtil.fail(500, "请先开通会员");
        }
        if (!userService.findById(userId).getHasPayDeposit()) {
            return ResponseUtil.fail(500, "请至会员页缴纳押金");
        }
        Integer memberRuleId = userMember.getMemberRuleId();
        LitemallMemberRule memberRule = memberRuleMapper.selectByPrimaryKey(memberRuleId);
//        int num = 0;
//
//        for (AdminRenOrderDetail adminRenOrderDetail : detailList) {
//            Integer bookNumber = adminRenOrderDetail.getBookNumber();
//            num += bookNumber;
//        }


//        for (Integer bookBoxId : rentOrderDto.getDetailList()) {
//            LitemallBookBox bookBox = bookBoxService.findById(bookBoxId);
//            if (bookBox != null) {
//                Integer number = bookBox.getNumber();
//                num += number;
//            }
//        }
        // todo  改为书位拦截
//        if (num != memberRule.getAvailableRentNumber()) {
//            return ResponseUtil.fail(500, "下单本书只能为" + memberRule.getAvailableRentNumber() + "本");
//        }



        if (checkHasBookToReturn(userId)) {
            return ResponseUtil.fail(500, "您尚有待还的书，请归还后再借");
        }
        if (addressId == null) {
            return ResponseUtil.fail(500, "请选择收货地址");
        }
        /* 更新订单表 */
        LitemallRentOrder rentOrder = new LitemallRentOrder();
        rentOrder.setUserId(userId);
        rentOrder.setUserName(userService.findById(userId).getNickname());
        rentOrder.setUserMemberId(userMember.getId());
        String consignee = checkedAddress.getName();
        rentOrder.setConsignee(consignee);
        String mobile = checkedAddress.getTel();
        rentOrder.setMobile(mobile);
        if (!StringUtils.isEmpty(remark)) {
            rentOrder.setRemark(remark);
        }

        String detailedAddress = checkedAddress.getProvince() + " " + checkedAddress.getCity() + " " + checkedAddress.getCounty() + " " + checkedAddress.getAddressDetail();
        rentOrder.setAddress(detailedAddress);
        rentOrder.setRentOrderStatus(RentOrderConstant.STATUS_WAIT);
        rentOrder.setRentOrderSn(SnUtil.generateOrderSn("rent"));
        rentOrder.setAddTime(LocalDateTime.now());
        rentOrder.setUpdateTime(LocalDateTime.now());
        rentOrderMapper.insertSelective(rentOrder);

        int count = 0;
        for (AdminRenOrderDetail adminRenOrderDetail : detailList) {
            Integer goodsId = adminRenOrderDetail.getGoodsId();
            LitemallGoods goods = goodsService.findById(goodsId);
            if (goods == null) {
                // 商品异常回退

                throw new BadRequestException(HttpStatus.BAD_REQUEST, "不存在" + goodsId + "的图书");
            }

            // 去查product
            List<LitemallGoodsProduct> litemallGoodsProducts = productService.queryByGid(goodsId);
            List<LitemallGoodsProduct> productsOld
                    = litemallGoodsProducts.stream().filter(item -> "旧".equals(item.getSpecifications())).collect(Collectors.toList());
            LitemallGoodsProduct litemallGoodsProduct = productsOld.get(0);

            if (litemallGoodsProduct.getNumber() < 0 || litemallGoodsProduct.getNumber() < adminRenOrderDetail.getBookNumber()) {
                throw new BadRequestException(HttpStatus.BAD_REQUEST, goods.getName() + " 库存不足");
            }

            if (goodsProductMapper.reduceStock(litemallGoodsProduct.getId(), adminRenOrderDetail.getBookNumber()) == 0) {
               //Integer goodsId = goodsProduct.getGoodsId();
                //LitemallGoods goods = goodsService.findById(goodsId);
                throw new BadRequestException(HttpStatus.BAD_REQUEST, goods.getName() + " 库存不足");
            }

            LitemallRentOrderDetail rentOrderDetail = new LitemallRentOrderDetail();
            rentOrderDetail.setUserId(userId);
            rentOrderDetail.setName(goods.getName());
            rentOrderDetail.setRentOrderId(rentOrder.getId());
            rentOrderDetail.setPrice(litemallGoodsProduct.getPrice());
            rentOrderDetail.setMemberPrice(litemallGoodsProduct.getMemberPrice());
            rentOrderDetail.setPicUrl(goods.getPicUrl());
            rentOrderDetail.setGoodsProductId(litemallGoodsProduct.getId());
            rentOrderDetail.setGoodsId(adminRenOrderDetail.getGoodsId());
            rentOrderDetail.setAuthor(goods.getAuthor());
            count += adminRenOrderDetail.getBookNumber();
            rentOrderDetail.setNumber(adminRenOrderDetail.getBookNumber());
            rentOrderDetail.setAddTime(LocalDateTime.now());
            rentOrderDetail.setUpdateTime(LocalDateTime.now());
            rentOrderDetailMapper.insertSelective(rentOrderDetail);
            // bookBoxMapper.deleteByPrimaryKey(bookBoxId);

        }


//        int count = 0;
//        /* 更新订单详情表 */
//        for (Integer bookBoxId : bookBoxIds) {
//            LitemallBookBox bookBox = bookBoxService.findById(bookBoxId);
//            LitemallGoodsProduct goodsProduct = goodsProductService.findById(bookBox.getGoodsProductId());
//            if (goodsProductMapper.reduceStock(goodsProduct.getId(), bookBox.getNumber()) == 0) {
//                Integer goodsId = goodsProduct.getGoodsId();
//                LitemallGoods goods = goodsService.findById(goodsId);
//                throw new BadRequestException(HttpStatus.BAD_REQUEST, goods.getName() + " 库存不足");
//            }
//            LitemallRentOrderDetail rentOrderDetail = new LitemallRentOrderDetail();
//            rentOrderDetail.setUserId(userId);
//            rentOrderDetail.setName(bookBox.getName());
//            rentOrderDetail.setRentOrderId(rentOrder.getId());
//            rentOrderDetail.setPrice(bookBox.getOriginalPrice());
//            rentOrderDetail.setMemberPrice(goodsProduct.getMemberPrice());
//            rentOrderDetail.setPicUrl(bookBox.getPicUrl());
//            rentOrderDetail.setGoodsProductId(bookBox.getGoodsProductId());
//            rentOrderDetail.setGoodsId(bookBox.getGoodsId());
//            rentOrderDetail.setAuthor(bookBox.getAuthor());
//            count += bookBox.getNumber();
//            rentOrderDetail.setNumber(bookBox.getNumber());
//            rentOrderDetail.setAddTime(LocalDateTime.now());
//            rentOrderDetail.setUpdateTime(LocalDateTime.now());
//            rentOrderDetailMapper.insertSelective(rentOrderDetail);
//            bookBoxMapper.deleteByPrimaryKey(bookBoxId);
//        }

        // TODO
        //   调用微信公众公众号发送信息
        //


        LitemallUser litemallUser = userMapper.selectByPrimaryKey(userId);
        // 获取用户信息
        String openid = litemallUser.getWeixinOpenid();

        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId("wOH6vtizP5Dnni4P5GCPaSFA-HX0WF4fCSYgo8_cl-w");
        //设置发送给哪个用户
        wxMpTemplateMessage.setToUser("o2mFx6hQ4X-vkExEUozjncLnry9k");
        //构建消息格式
        List<WxMpTemplateData> list = Arrays.asList(
                new WxMpTemplateData("first", "您的订单已经确认成功"),
                //订单号
                new WxMpTemplateData("keyword1", rentOrder.getRentOrderSn()),
                new WxMpTemplateData("keyword2", "共计图书：" + count + "本"),
                new WxMpTemplateData("keyword3", ""),
                new WxMpTemplateData("remark", "请您阅读愉快")
        );
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(list);
//        try {
//            //发送模板
//            //String s = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
//           // System.out.println(s);
//        } catch (WxErrorException e) {
//            System.out.println("===========发送模板信息失败===========");
//            e.printStackTrace();
//
//        }


        return ResponseUtil.ok(rentOrder);
    }
}
